package com.changge.module.system.service.menu;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.changge.common.core.utils.IdUtil;
import com.changge.common.models.domain.system.menu.MenuRole;
import com.changge.common.models.dto.system.menu.MenuRoleDTO;
import com.changge.common.models.enums.system.log.OperateType;
import com.changge.common.models.vo.system.menu.MenuTreeVO;
import com.changge.common.redis.enums.RedisKey;
import com.changge.common.redis.service.IRedisService;
import com.changge.module.system.mapper.menu.MenuMapper;
import com.changge.module.system.mapper.menu.MenuRoleMapper;
import com.changge.system.facade.annotation.OperationLog;
import com.changge.system.facade.service.menu.IMenuRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 菜单角色关联业务逻辑接口实现类
 *
 * @author zhangrongkang
 * @since 2023/12/18
 */
@Slf4j
@Service
public class MenuRoleServiceImpl implements IMenuRoleService {

    @Autowired
    private IdUtil idUtil;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private MenuRoleMapper menuRoleMapper;

    @Autowired
    private IRedisService redisService;

    /**
     * 获取当前角色已有的菜单权限
     *
     * @param roleId 角色权限
     * @return 当前角色的具备的菜单权限
     */
    @Override
    public List<String> listMenuIdByRoleId(Long roleId) {
        List<Long> ids = menuRoleMapper.listMenuIdByRoleId(roleId);
        List<String> checkIds = new ArrayList<>();
        for (Long id : ids) {
            checkIds.add(String.valueOf(id));
        }
        return checkIds;
    }

    /**
     * 获取所有菜单树型数据
     *
     * @return 菜单树型数据集合
     */
    @Override
    public List<MenuTreeVO> listAllMenuTree() {
        // 获取到所有树型数据
        return menuMapper.listMenuTree();
    }

    /**
     * 保存菜单角色关联数据
     *
     * @param menuRoleDTO 角色菜单关联数据传输对象
     * @return 是否保存成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @OperationLog(type = OperateType.ADD)
    public Boolean save(MenuRoleDTO menuRoleDTO) {
        Long roleId = menuRoleDTO.getRoleId();
        // 清除Redis中当前角色对应的菜单权限
        String key = RedisKey.SYSTEM_MENU_KEY.getKey() + roleId;
        redisService.del(key);
        // 删除当前角色所有的菜单权限
        menuRoleMapper.delete(new QueryWrapper<MenuRole>().eq("role_id", roleId));
        List<Long> menuIds = menuRoleDTO.getMenuIds();
        // 重新批量添加
        List<MenuRole> menuRoles = new ArrayList<>();
        for (Long menuId : menuIds) {
            menuRoles.add(MenuRole.builder().id(idUtil.nextId()).roleId(roleId).menuId(menuId).build());
        }
        return menuRoleMapper.insertBatch(menuRoles) == menuRoles.size() ;
    }
}
